package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.enums.RedisLockPrefixEnum;
import com.lcf.framework.utils.RedisLockUtils;
import com.lcf.framework.utils.UserUtils;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.GoodsCartDao;
import com.lcf.system.dto.GoodsCartDTO;
import com.lcf.system.entity.GoodsCart;
import com.lcf.system.query.GoodsCartPageQuery;
import com.lcf.system.service.GoodsCartService;
import com.lcf.system.vo.GoodsCartVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 购物车(GoodsCart)表服务实现类
 *
 * @author lcf
 * @since 2025-05-02 11:55:00
 */
@Service("goodsCartService")
public class GoodsCartServiceImpl extends ServiceImpl<GoodsCartDao, GoodsCart> implements GoodsCartService {
    @Resource
    private RedisLockUtils redisLockUtils;

    @Override
    public boolean addGoodsCart(GoodsCartDTO dto) {
        long userId = UserUtils.getUserId();
        return redisLockUtils.tryLock(RedisLockPrefixEnum.ADD_GOODS_CART, dto.getGoodsId() + ":" + userId, () -> {
            GoodsCart goodsCart = Db.lambdaQuery(GoodsCart.class)
                    .eq(GoodsCart::getGoodsId, dto.getGoodsId())
                    .eq(GoodsCart::getUserId, userId)
                    .one();
            if (goodsCart != null) {
                return Db.lambdaUpdate(GoodsCart.class)
                        .eq(GoodsCart::getId, goodsCart.getId())
                        .set(GoodsCart::getGoodsNum, goodsCart.getGoodsNum() + dto.getGoodsNum())
                        .update();
            }

            GoodsCart cart = BeanUtil.copyProperties(dto, GoodsCart.class);
            cart.setUserId(userId);

            return cart.insert();
        });
    }

    @Override
    public boolean deleteGoodsCart(long id) {
        return removeById(id);
    }

    @Override
    public boolean updateGoodsCart(long id, GoodsCartDTO dto) {
        GoodsCart cart = BeanUtil.copyProperties(dto, GoodsCart.class);
        cart.setId(id);
        return cart.updateById();
    }

    @Override
    public GoodsCartVO getGoodsCart(long id) {
        GoodsCart cart = getById(id);
        return BeanUtil.copyProperties(cart, GoodsCartVO.class);
    }

    @Override
    public PageVO<GoodsCartVO> getGoodsCartList(GoodsCartPageQuery query) {
        Page<GoodsCart> page = Db.lambdaQuery(GoodsCart.class)
                .eq(GoodsCart::getUserId, UserUtils.getUserId())
                .orderByDesc(GoodsCart::getCreateTime)
                .page(query.toPage());
        return new PageVO<>(page, GoodsCartVO.class);
    }
}

